package net.sos.services.impl;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.activation.DataHandler;
import javax.jws.WebService;

import net.sos.services.contract.IFirstService;
import net.sos.services.valueobject.Employee;
import net.sos.services.valueobject.Message;

import com.sun.istack.ByteArrayDataSource;

/**
 * @author SANJAY
 * 
 */
@WebService(name = "First", serviceName = "FirstService", targetNamespace = "http://sos.net/Services", endpointInterface = "net.sos.services.contract.IFirstService", portName = "MyPort")
public class FirstServiceImpl implements IFirstService {

   @Override
   public String sayHello(String name) {
      return hellofyName(name);
   }

   @Override
   public String[] sayHellosi(String[] names) {
      for (int i = 0; i < names.length; ++i) {
         names[i] = hellofyName(names[i]);
      }
      return names;
   }

   private String hellofyName(String name) {
      return "Hello " + name + "!";
   }

   @Override
   public Employee getEmployee(String employeeId) {
      Employee employee = new Employee();
      employee.setAge(25);
      employee.setName("sanjay" + employeeId);
      return employee;
   }

   @Override
   public Message giveOneGetN(Message inMessage) {
      try {
         InputStream in = inMessage.getContent().getInputStream();
         ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
         byte[] buffer = new byte[1024];

         int cnt = -1;
         while ((cnt = in.read(buffer)) != -1) {
            byteOut.write(buffer, 0, cnt);
         }
         byteOut.write("\nOH noes!".getBytes());
         in.close();

         ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(
               byteOut.toByteArray(), byteOut.toByteArray().length,
               "text/plain");
         inMessage.setContent(new DataHandler(byteArrayDataSource));
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      return inMessage;
   }

}
